package pub.cleangao.mybatis;


import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import pub.cleangao.mybatis.config.Config;
import pub.cleangao.mybatis.config.EnhanceProperties;
import pub.cleangao.mybatis.spi.SpiContext;
import pub.cleangao.mybatis.structure.ClassFileScanner;
import pub.cleangao.mybatis.structure.MybatisXmlReload;

import java.util.List;


/**
 * 启动此组件服务
 */
@Slf4j
public class Component {


    /**
     * 启动服务组件
     *
     * @param sqlSessionFactories MyBatis的(全部)SqlSessionFactory
     */
    public static void start(List<SqlSessionFactory> sqlSessionFactories) {
        generateMyBatisDefinitions();
        startServe(sqlSessionFactories);
        log.info("MyBatis-Enhance component is running, powered by clean.gao");
    }



    /**
     * 生成MyBatis Enhance的增强文件，并加载元数据配置
     */
    private static void generateMyBatisDefinitions() {
        EnhanceProperties properties = Config.loadMyBatisEnhanceConfig();
        // 1. 扫描entity文件 （必须在扫描mapper前）
        String entityPackage = properties.getEntityPackage();
        if (properties.isScanRoot()) {
            entityPackage = properties.getModuleRootPackage();
        }
        ClassFileScanner.buildDataStructureBy(entityPackage);

        // 2. 扫描MapperInterface; 生成Mapper.xml文件
        String mapperPackage = properties.getMapperPackage();
        if (properties.isScanRoot()) {
            mapperPackage = properties.getModuleRootPackage();
        }
        ClassFileScanner.buildExecutorProxyBy(mapperPackage);
    }




    /**
     * 重新加载Mapper.xml文件
     */
    private static void startServe(List<SqlSessionFactory> sqlSessionFactoryList) {
        try {
            SpiContext.setSqlSessionFactory(sqlSessionFactoryList);
            new MybatisXmlReload(sqlSessionFactoryList).xmlReload();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
